<template>
  <div class="chat-container">
    <n-flex vertical style="height: 100%">
      <!-- 滚动区域 -->
      <n-scrollbar>
        <div class="messages">
          <div v-for="(msg, index) in messages" :key="index" :class="msg.role">

            <n-card v-if="msg.role=='assistant'" content-style="padding:0px;" class="message">
              <MdPreview :modelValue="msg.displayContent" :theme="isDark?'dark':'light'" :autoFoldThreshold="200"/>
            </n-card>
            <n-card v-else="msg.role=='assistant'" content-style="padding:0px;" class="message" style="width: auto">
              <MdPreview :modelValue="msg.displayContent" :theme="isDark?'dark':'light'" :autoFoldThreshold="200"/>
            </n-card>
          </div>
        </div>
      </n-scrollbar>

      <!-- 底部固定区域 -->
      <div :style="{  padding: '16px', textAlign: 'left' }">
        <div class="input-area">

          <n-mention
              type="textarea"
              v-model:value="inputMessage"
              @keyup.enter="handleEnter"
              :prefix="['/']"
              placeholder="来说点什么吧🤓 👉(Shift+Enter=换行)"
              :disabled="isLoading"
              :options="mention0ptions"
              autosize
          />
          <n-button @click="sendMessage" :disabled="isLoading">发送</n-button>
        </div>
      </div>
    </n-flex>


  </div>
</template>

<script setup lang="ts">
import {computed, ref} from 'vue';
import {getWord} from '@/components/cueWord/cueWordUtils';
import {MdPreview} from 'md-editor-v3';
import 'md-editor-v3/lib/style.css';
import {useSettingsStore} from "@/stores/settingStore.ts";
import {FetchChatClient, OpenAIClient} from "@/utils/apiClients.ts";

const settingsStore = useSettingsStore();
settingsStore.initializeValues(); // 初始化字段值
const inputMessage = ref(''); // 用户输入的消息
const messages = ref<{ role: string; content: string; displayContent: string }[]>([]); // 聊天记录
const isLoading = ref(false); // 是否正在加载
// 绑定 selectedModel 和 useStream
const selectedModel = computed({
  get: () => settingsStore.values.selectedModel as string,
  set: (value) => settingsStore.setValue('selectedModel', value),
});

const useStream = computed({
  get: () => settingsStore.values.useStream as boolean,
  set: (value) => settingsStore.setValue('useStream', value),
});
const genHywayJs = computed({
  get: () => settingsStore.values.genHywayJs as boolean,
  set: (value) => settingsStore.setValue('genHywayJs', value),
});

const props = defineProps<{
  isDark: boolean
}>()
const options =
    [
      {
        label: 'DeepSeek V3',
        value: 'deepseek-chat'
      },
      {
        label: 'DeepSeek' + ' R1',
        value: 'deepseek-reasoner'
      },
      {
        label: 'DeepSeek-R1' + ' 8B',
        value: 'deepseek-r1:8b'
      }
    ]
const mention0ptions = [
  {
    label: '担任Hyway脚本生成器',
    value: '07akioni'
  },
  {
    label: '担任正则表达式生成器',
    value: 'star-kirby'
  }
]
const handleEnter = (event: KeyboardEvent) => {
  if (event.shiftKey) {
    // 按下 Shift + Enter 换行
    return; // 允许默认换行行为
  } else {
    // 按下 Enter 发送消息
    event.preventDefault(); // 阻止默认换行行为
    sendMessage(); // 触发发送逻辑
  }
};
// const clients = {
//   deepseek: new FetchChatClient({
//     apiKey: import.meta.env.VITE_DEEPSEEK_API_KEY,
//     baseURL: 'https://api.deepseek.com',
//     model: 'deepseek-chat',
//   }),
//
//   openai: new OpenAIClient({
//     apiKey: 'your-openai-key',
//     model: 'gpt-4',
//   }),
// };
const sendMessage = async () => {
  if (!inputMessage.value.trim() || isLoading.value) return;
  // 添加用户消息
  const reqMessage=JSON.parse(JSON.stringify(messages.value));
  if(genHywayJs.value){
    reqMessage.push({role: 'system', content: getWord(), displayContent: ''});
  }
  messages.value.push({role: 'user', content: inputMessage.value, displayContent: inputMessage.value});
  reqMessage.push({role: 'user', content: inputMessage.value, displayContent: inputMessage.value})
  isLoading.value = true;
  inputMessage.value = '';
  reqMessage.forEach(item => delete item.displayContent);
  try {
    if (useStream.value) {
      const openai= new OpenAIClient({
        baseURL:'https://api.deepseek.com',
       apiKey: `${import.meta.env.VITE_DEEPSEEK_API_KEY}`,
        model: selectedModel.value
    })
      // 创建 AI 消息条目
      messages.value.push({role: 'assistant', content: '', displayContent: ''});

      // 获取最新的 AI 消息条目
      const aiMessage = messages.value[messages.value.length - 1];
      const fullContent = await openai.sendRequest(
          [...reqMessage, { role: 'user', content: inputMessage.value }],
          useStream.value,
          '',
          (chunk) => {
            console.error('chunk',chunk)
            aiMessage.content += chunk;
            aiMessage.displayContent = aiMessage.content;
          }
      );
      // 确保最终结果更新
      aiMessage.displayContent = fullContent;
      isLoading.value = false;
      // const response = await fetch('https://api.deepseek.com/chat/completions', {
      //   method: 'POST',
      //   headers: {
      //     'Content-Type': 'application/json',
      //     Accept: 'application/json',
      //     Authorization: `Bearer ${import.meta.env.VITE_DEEPSEEK_API_KEY}`,
      //   },
      //   body: JSON.stringify({
      //     messages:reqMessage,
      //     model: selectedModel.value,
      //     temperature: 1,
      //     stream: true, // 启用流式输出
      //   }),
      // });
      //
      // if (!response.ok) {
      //   throw new Error(`请求失败: ${response.statusText}`);
      // }
      //
      // // 创建 AI 消息条目
      // messages.value.push({role: 'assistant', content: '', displayContent: ''});
      //
      // // 获取最新的 AI 消息条目
      // const aiMessage = messages.value[messages.value.length - 1];
      //
      // // 处理分块数据
      // const reader = response.body?.getReader();
      // const decoder = new TextDecoder('utf-8');
      // let buffer = '';
      //
      // if (reader) {
      //   while (true) {
      //     const {done, value} = await reader.read();
      //     if (done) break; // 流式传输结束
      //
      //     const chunk = decoder.decode(value, {stream: true});
      //     buffer += chunk;
      //
      //     // 处理缓冲区中的数据
      //     const lines = buffer.split('\n').filter((line) => line.trim());
      //     console.error('lines',lines)
      //     lines.forEach((line) => {
      //       if (line.startsWith('data: ')) {
      //         const data = line.replace('data: ', '').trim();
      //         if (data === '[DONE]') return; // 流式传输结束
      //         try {
      //           const parsed = JSON.parse(data);
      //           if (parsed.choices && parsed.choices[0].delta.content) {
      //             const newContent = parsed.choices[0].delta.content;
      //             aiMessage.content += newContent; // 更新消息内容
      //             aiMessage.displayContent = (aiMessage.content);
      //           }
      //         } catch (error) {
      //           console.error('解析流式数据错误:', error);
      //         }
      //       }
      //     });
      //
      //     // 清空已处理的数据
      //     buffer = buffer.slice(lines.join('\n').length);
      //   }
      //   console.error('aiMessage',aiMessage)
      //   isLoading.value = false; // 流式传输完成
      // }
    } else {
      // 非流式输出 https://api.deepseek.com/chat/completions
      const response = await fetch('http://192.168.0.111:11434/v1/chat/completions', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Accept: 'application/json',
          Authorization: `Bearer ${import.meta.env.VITE_DEEPSEEK_API_KEY}`,
        },
        body: JSON.stringify({
          messages: reqMessage,
          model: selectedModel.value,
          temperature: 1,
          max_tokens: 2048,
          stream: false,
        }),
      });

      const data = await response.json();
      console.error('content', data.choices[0].message.content)
      // 添加 AI 回复
      const aiMessage = {
        role: 'assistant',
        content: data.choices[0].message.content,
        displayContent: data.choices[0].message.content,
      };
      messages.value.push(aiMessage);
      isLoading.value = false;
    }
  } catch (error) {
    console.error('Error:', error);
    messages.value.push({
      role: 'assistant',
      content: '请求失败，请稍后重试。',
      displayContent: '请求失败，请稍后重试。',
    });
    isLoading.value = false;
  }
};
</script>


<style>

.chat-container {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  height: calc(100% - 40px);
}

.messages {
  margin-bottom: 20px;
}

.message {
  text-align: left;
  margin-bottom: 10px;
  padding: 0px;
}

.user {
  text-align: right;
}

.assistant {
  text-align: left;
}

.input-area {
  display: flex;
  gap: 10px;
  align-items: center;
}

input {
  flex: 1;
  padding: 10px;
}

button {
  padding: 10px 20px;
}
</style>
